<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace YMApi\Model;

use ClassesWithParents\D;
use YMApi\Service\BuyNowGoodsService;
use YMApi\Service\PromoteService;
use Think\Cache\Driver\Db;
use Think\Exception;
use Think\Model;

class GoodsModel extends Model
{
    protected $tableName = 'goods';

    public function get_goods_sn($goods_id){
        $goodsSn = D('Goods')->where(array('goods_id'=>$goods_id))->getField('goods_sn');
        return $goodsSn;
    }
    /*
     * 获取商品详情
     */
    public function get_goods_details($goods_id, $uid = 0, $wid = 0)
    {
        $where = array(
            'g.goods_id' => $goods_id,
            'mp.user_rank' => 2
        );
// 		if($wid){
// 		    $where['gs.wid']=$wid;
// 		    $res = $this->alias ( 'g' )
// 		           ->field ( 'g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.virtual_sales' )
// 		           ->join ( 'left join ' . C ( 'DB_PREFIX' ) . 'member_price mp on g.goods_id=mp.goods_id' )
// 		           ->join ( 'left join ' . C ( 'DB_PREFIX' ) . 'goods_storage gs on g.goods_id=gs.goods_id' )
// 		           ->where ($where)
// 		           ->find ();
// 		}else{
// 		    $res = $this->alias ( 'g' )->field ( 'g.show_desc,g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.virtual_sales' )->join ( 'left join ' . C ( 'DB_PREFIX' ) . 'member_price mp on g.goods_id=mp.goods_id' )->where ( $where )->find ();
// 		}

//		$res = $this->alias('g')->field('g.show_desc,g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.virtual_sales,g.min_buy_num,g.origin, g.promote_goods_number, g.promote_today_number')->join('left join ' . C('DB_PREFIX') . 'member_price mp on g.goods_id=mp.goods_id')->where($where)->find();
        $res = $this->alias('g')
            ->field('g.show_desc,g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.virtual_sales,g.min_buy_num,g.origin, g.promote_goods_number, g.promote_today_number, g.is_buynow, g.is_offline, c.cat_name')
            ->join('left join ' . C('DB_PREFIX') . 'member_price mp on g.goods_id=mp.goods_id')
            ->join('left join '.C('DB_PREFIX') . 'category c on c.cat_id = g.cat_id')
            ->where($where)->find();

        if ($res) {
            $picture_list = $this->get_goods_gallery($goods_id);
            $res['goods_picture_list'] = $picture_list;
            if (!empty ($picture_list)) {
                $picture = current($picture_list);
                $res ['goods_img'] = img_init($picture ['img_url']);
            }else{
                $res ['goods_img'] = img_init('');
            }
            if ($res ['spec_value']) {
//                $res ['spec_value'] = $res ['spec_value'];
//                $res ['spec_unit'] = $res ['spec_unit'];
            } elseif ($res ['goods_weight']) {
                $res ['spec_value'] = $res ['goods_weight'] * 1000;
                $res ['spec_unit'] = "g";
            }
            if ($uid) {
                $map['user_id'] = $uid;
                $map['goods_id'] = $goods_id;
                $collect_rec_id = M("collect_goods")->where($map)->getField('rec_id');
                if (!empty($collect_rec_id)) {
                    $res ['is_collect'] = 1;
                } else {
                    $res ['is_collect'] = 0;
                }
            } else {
                $res ['is_collect'] = 0;
            }

            if ($res ['show_desc'] != 1) {
                unset($res ['goods_desc']);
            }else{
                $res ['goods_desc'] = $this->convert_desc_img_url($res ['goods_desc']);
            }

//			$promote_price = bargain_price($res['promote_price'], $res['promote_start_date'], $res['promote_end_date']);
//
//			if($promote_price > 0){
//				$promoteService = new PromoteService();
//				$res['promote_message'] = $promoteService->getPromoteGoodsNumber($res)->getNumberMessage();
//				//            促销时间
//				$res['promote_start_date'] = date('Y-m-d', localtotime($res['promote_start_date']));
//				$res['promote_end_date'] = date('Y-m-d', localtotime($res['promote_end_date']));
//			}else{
//				$res['promote_price'] = 0;
//				$res['promote_start_date'] = 0;
//				$res['promote_end_date'] = 0;
//				$res['promote_message'] = '';
//			}

//            商品活动价格数据处理
//            $promote_price = bargain_price($res['promote_price'], $res['promote_start_date'], $res['promote_end_date']);
//			促销价
            if($res['is_buynow'] == 0){
                $promoteService = new PromoteService();
                $res = $promoteService->formatPromoteData($res);

            }
//			秒杀商品数据处理
            else if ($res['is_buynow'] == 1)
			{
				$buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
				$res = $buyNowGoodsService->handleBuyNowGoodsData($res);
			}
////            不为促销价时候清空值
//			else if ($res['is_buynow'] == 0)
//			{
//				$res['promote_price'] = 0;
//				$res['promote_start_date'] = 0;
//				$res['promote_end_date'] = 0;
//				$res['promote_message'] = '';
//			}
//			不为秒杀价时候清空值
//			else if ($res['is_buynow'] == 1)
//			{
//				$res['buy_now_end_date'] = 0;
//				$res['buy_now_start_date'] = 0;
//				$res['buy_now_end_time'] = 0;
//				$res['buy_now_start_time'] = 0;
//				$res['buy_now_price'] = 0;
//				$res['buy_now_status'] = 0;
//				$res['buy_now_message'] = '';
//				unset($res['promote_end_date'], $res['promote_start_date'], $res['promote_goods_number'], $res['promote_today_number'], $res['promote_price']);
//			}

////            促销价
//            if(localtotime($res['promote_end_date']) > gmtime()){
////            促销时间
//                $res['promote_start_date'] = date('Y-m-d', localtotime($res['promote_start_date']));
//                $res['promote_end_date'] = date('Y-m-d', localtotime($res['promote_end_date']));
//            }else{
//                $res['promote_price'] = 0;
//                $res['promote_start_date'] = 0;
//                $res['promote_end_date'] = 0;
//            }

            /**
             * 第二件半价
             */
//            $favourableModel = D('FavourableActivity');
//            if($favourableData = $favourableModel->get_is_discount($uid, $goods_id)){
//                $res['is_discount'] = 1;
//                $res['discount_start_time'] = date('Y-m-d', $favourableData['start_time']);
//                $res['discount_end_time'] = date('Y-m-d', $favourableData['end_time']);
//            }


//            $res['vip_price']  = $this->get_vip_price($goods_id, $uid);
//            dd($res['goods_img']);
//            if(!file_exists($res['goods_img'])){
//                $ossConfig = C('OSS');
//                $res['goods_img'] = $ossConfig['image'] . $res['goods_img'];
//            }

			$res['vip_price'] = $this->get_vip_price($goods_id, $uid);
            $res['true_vip_price'] = $this->get_vip_price_for_all($goods_id);
            $res['market_price'] = trim($this->get_vip_price_for_all($goods_id,1));    //市场价使用注册会员价
            $res['is_presell']=(int)$res['is_presell'];
            if($res['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $res['is_presell'] = D('Goodsstorage')->check_whether_presell($res['goods_id'], $wid);
            }

            if ($res['is_presell']) {
                if ($res['delivery_type'] == 1) {//分段发货
                    $Goodspreselltime = D('Goodspreselltime');
                    if ($Goodspreselltime->check_shipping_goodspreselltime($res['goods_id'])) {//检查预售商品是否设置发货配送时间
                        $preselltimeres = $Goodspreselltime->check_shippingtime($res['goods_id'], time());
                        if ($preselltimeres) {
                            $res['preselltimeres'] = array('delivery_time' => $preselltimeres['delivery_time']);
                        } else {
                            $res['preselltimeres'] = array('delivery_time' => '');
                        }
                    } else {
                        $res['preselltimeres'] = array('delivery_time' => '');
                    }
                } elseif ($res['delivery_type'] == 2) {//定时方式
                    if ($res['delivery_cycle']) {
                        $gmd = local_date('Y-m-d', gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd . ' +' . $res['delivery_cycle'] . ' day ' . C('DEFAULT_PRESELL_TIME_H')));
                        $res['preselltimeres'] = array('delivery_time' => $goods_presell_time);
                    } else {
                        $res['preselltimeres'] = array('delivery_time' => '');
                    }
                } else {
                    $res['preselltimeres'] = array('delivery_time' => '');
                }
            } else {
                $goodsstorage = D('Goodsstorage')->get_warehous_goods($wid, $res['goods_id']);
                if ($goodsstorage) {
                    $res['goods_number'] = $goodsstorage['practical_num'];
                } else {
                    $res['goods_number'] = 0;
                }
                $res['preselltimeres'] = array('delivery_time' => '');
            }

            // 取得优惠活动
            $favourable_list = D('NewCart')->favourable_list_flow($uid,$wid);
            $res['favourable_list'] = $this->get_goods_favourable_list($favourable_list,$res);

            return $res;
        } else {
            return false;
        }
    }


    /**
     * 转换商品详情内容中的图片地址，转为绝对路径
     * @param $goods_desc
     * @return mixed
     */
    public function convert_desc_img_url($goods_desc){
        if(!empty($goods_desc)){
            $host = C('CDN_IMG_HOST');
            preg_match_all("/<img.*?src=\"(.*?)\".*?>/is", $goods_desc,$matches);   //获取详情中img标签的src地址
            if(!empty($matches) && !empty($matches[1])){
                $img_url_list = array_unique($matches[1]);  //处理重复内容
                foreach($img_url_list as $url){
                    if(strpos(strtolower($url),'http://')===false && strpos(strtolower($url),'https://')===false){
                        $goods_desc = str_replace($url,$host.$url,$goods_desc);
                    }
                }
            }
        }
        return $goods_desc;
    }


    /**
     * 获得指定商品的相册
     *
     * @access  public
     * @param   integer $goods_id
     * @return  array
     */
    public function get_goods_gallery($goods_id, $real_url = false)
    {
        $sql = 'SELECT img_id, img_url, thumb_url, img_desc' .
            ' FROM ' . C('DB_PREFIX') .
            "goods_gallery WHERE goods_id = '$goods_id' LIMIT " . C('goods_gallery_number');
        $row = $this->query($sql);
        /* 格式化相册图片路径 */
        if ($real_url) {
            foreach ($row as $key => $gallery_img) {
                $row[$key]['img_url'] = img_init(get_image_path($goods_id, img_init($gallery_img['img_url']), false, 'gallery'));
                $row[$key]['thumb_url'] = img_init(get_image_path($goods_id, img_init($gallery_img['thumb_url']), true, 'gallery'));
                $row[$key]['img_desc'] = $gallery_img['img_desc'];
            }
        }
        return $row;
    }

    /*
     * 获取限购商品详情
     * */
    public function get_quota_goods_details($act_id, $goods_id, $uid, $wid = 0)
    {
        $activity = D('FavourableActivity');
        $activity_info = $activity->favourable_info($act_id);

        foreach ($activity_info['quota'] as $quota) {
            if ($quota['id'] == $goods_id) {
                $quota_goods = $quota;
                break;
            }
        }
        /* if (empty($quota_goods)) {
            returnApiError('此活动不存在此商品或已取消活动');
        } */
        $where = array('g.goods_id' => $goods_id, 'mp.user_rank' => 2);
//     	if($wid){
//     		$where['gs.wid']=$wid;
//     		$res = $this->alias ( 'g' )
//     		->field ( 'g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.virtual_sales' )
//     		->join ( 'left join ' . C ( 'DB_PREFIX' ) . 'member_price mp on g.goods_id=mp.goods_id' )
//     		->join ( 'left join ' . C ( 'DB_PREFIX' ) . 'goods_storage gs on g.goods_id=gs.goods_id' )
//     		->where ($where)
//     		->find ();
//     	}else{
// 	    	$res=$this->alias('g')->field('g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.virtual_sales')
// 	    	->join('left join '.C('DB_PREFIX').'member_price mp on g.goods_id=mp.goods_id')
// 	    	->where($where)
// 	    	->find();
//     	}
//		$res = $this->alias('g')->field('g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.virtual_sales,g.origin, g.promote_goods_number, g.promote_today_number')
        $res = $this->alias('g')->field('g.goods_id,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,mp.user_price as vip_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.virtual_sales,g.origin, g.promote_goods_number, g.promote_today_number, g.is_buynow')
            ->join('left join ' . C('DB_PREFIX') . 'member_price mp on g.goods_id=mp.goods_id')
            ->where($where)
            ->find();
        if ($res) {
            $res['quota_price'] = $quota_goods['price'];
            $res['quota_count'] = $quota_goods['count'];
            $res['quota_status'] = $quota_goods['status'];
            $res['is_quota'] = $act_id;
            $picture_list = $this->get_goods_gallery($goods_id);
            $res['goods_picture_list'] = $picture_list;

//            促销价
			$res['promote_price'] = bargain_price($res['promote_price'], $res ['promote_start_date'], $res ['promote_end_date']);
			if ($res['promote_price'] > 0) {
				$res['promote_start_date'] = date('Y-m-d', localtotime($res['promote_start_date']));
				$res['promote_end_date'] = date('Y-m-d', localtotime($res['promote_end_date']));
				$promoteService = new PromoteService();
				$res['promote_message'] = $promoteService->getPromoteGoodsNumber($res)->getNumberMessage();
			}
//            $res['promote_price'] = bargain_price($res['promote_price'], $res ['promote_start_date'], $res ['promote_end_date']);
//            if ($res['is_buynow'] == 0 || $res['is_promote']) {
//				$promoteService = new PromoteService();
//				$res = $promoteService->formatPromoteData($res);
//            }

            if (!empty($picture_list)) {
                $picture = current($picture_list);
                $res['goods_img'] = img_init($picture['img_url']);
            }
            if ($uid) {
                $map['user_id'] = $uid;
                $map['goods_id'] = $goods_id;
                $collect_rec_id = M("collect_goods")->where($map)->getField('rec_id');
                if (!empty($collect_rec_id)) {
                    $res ['is_collect'] = 1;
                } else {
                    $res ['is_collect'] = 0;
                }
            } else {
                $res ['is_collect'] = 0;
            }
            if ($res ['show_desc'] != 1) {
                unset($res ['goods_desc']);
            }
            $res['is_presell']=(int)$res['is_presell'];
            if($res['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $res['is_presell'] = D('Goodsstorage')->check_whether_presell($res['goods_id'], $wid);
            }
            if ($res['is_presell']) {
                if ($res['delivery_type'] == 1) {//分段发货
                    $Goodspreselltime = D('Goodspreselltime');
                    if ($Goodspreselltime->check_shipping_goodspreselltime($res['goods_id'])) {//检查预售商品是否设置发货配送时间
                        $preselltimeres = $Goodspreselltime->check_shippingtime($res['goods_id'], time());
                        if ($preselltimeres) {
                            $res['preselltimeres'] = array('delivery_time' => $preselltimeres['delivery_time']);
                        } else {
                            $res['preselltimeres'] = array('delivery_time' => '');
                        }
                    } else {
                        $res['preselltimeres'] = array('delivery_time' => '');
                    }
                } elseif ($res['delivery_type'] == 2) {//定时方式
                    if ($res['delivery_cycle']) {
                        $gmd = local_date('Y-m-d', gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd . ' +' . $res['delivery_cycle'] . ' day ' . C('DEFAULT_PRESELL_TIME_H')));
                        $res['preselltimeres'] = array('delivery_time' => $goods_presell_time);
                    } else {
                        $res['preselltimeres'] = array('delivery_time' => '');
                    }
                } else {

                }
            } else {
                $goodsstorage = D('Goodsstorage')->get_warehous_goods($wid, $res['goods_id']);
                if ($goodsstorage) {
                    $res['goods_number'] = $goodsstorage['practical_num'];
                } else {
                    $res['goods_number'] = 0;
                }
                $res['preselltimeres'] = array('delivery_time' => '');
            }

            return $res;
        } else {
            return false;
        }
    }

    /**
     * 获取当前商品正在参与的活动列表，不包括抢购活动
     * @param $favourable_list
     * @param $goods
     * @return array
     */
    public function get_goods_favourable_list($favourable_list,$goods){
        $goods_id = $goods['goods_id'];
        $goods_cate = $goods['cat_id'];
        $goods_brand= $goods['brand_id'];
        //商品可参与的活动列表
        $goods_activity_list = array();

        foreach ($favourable_list as $f_key => $f_avl) {
            //普通商品，获取商品的活动信息
            $act_range_ext = explode(',', $f_avl['act_range_ext']);
            if ($f_avl['act_range'] == 0 || ($f_avl['act_range'] == 1 && in_array($goods_cate, $act_range_ext)) || ($f_avl['act_range'] == 2 && in_array($goods_brand, $act_range_ext)) || ($f_avl['act_range'] == 3 && in_array($goods_id, $act_range_ext))) {
                //商品可参与的活动
                $goods_activity = array();
                $goods_activity['act_id'] = $f_avl['act_id'];
                $goods_activity['act_name'] = $f_avl['act_name'];
                $goods_activity['act_tag'] = D('NewCart')->check_activity_tag($f_avl['act_type'],$f_avl['gift']);
                $goods_activity_list[] = $goods_activity;
            }

        }

        return $goods_activity_list;
    }

    /**
     * 通过goods_sn返回商品id
     * Created by Jerry
     * @param $goods_sn
     * @return mixed
     */
    public function get_goods_by_goods_sn($goods_sn)
    {
        $where = array(
            'goods_sn'      =>  $goods_sn,
            'goods_number'  =>  array('GT', 0),
            'is_on_sale'    =>  array('EQ', 1),
        );

        return $this->field('goods_id,goods_sn,goods_name,market_price,shop_price,goods_number,is_on_sale')->where($where)->find();
    }


    /*
     * 获取促销商品列表
     * salestype    默认为0 0-新品  1-精品  2-热销  3-特价促销
     * */

    public function select_salesgoods_list($salestype = 0, $page, $wid = 0)
    {
        if ($salestype == 0) {
            $where = array('g.is_new' => 1);
        } elseif ($salestype == 1) {
            $where = array('g.is_best' => 1);
        } elseif ($salestype == 2) {
            $where = array('g.is_hot' => 1);
        } elseif ($salestype == 3) {
            $where = array('g.is_promote' => 1);
        }
        if ($wid) {
            $where['gs.wid'] = $wid;
        }
        $count = $this->get_goodscount($where);
        $pagearr = show_page($count, $page);
        if ($page >= $pagearr['pagecount']) {
            $is_last = 1;
        } else {
            $is_last = 0;
        }
        if ($wid) {
            $res = $this->alias('g')
                ->field('g.goods_id,gs.wid,g.goods_sn,g.goods_name,g.goods_name_style,g.cat_id,g.click_count,g.brand_id,g.goods_number,g.goods_weight,g.shop_price,g.market_price,g.promote_price,g.promote_start_date,g.promote_end_date,g.warn_number,g.goods_brief,g.goods_desc,g.goods_thumb,g.goods_img,g.original_img,g.is_real,g.extension_code,g.is_on_sale,g.is_alone_sale,g.integral,g.add_time,g.is_delete,g.is_new,g.is_hot,g.is_promote,g.bonus_type_id,g.last_update,g.goods_type,g.seller_note,g.give_integral')
                ->where($where)
                ->join(C('DB_PREFIX') . 'goods_storage as gs on gs.goods_id=g.goods_id')
                ->limit($pagearr['firstpage'] . ',' . C('page_size'))
                ->order('g.last_update desc,g.add_time desc,g.goods_id desc')
                ->select();
        } else {
            $res = $this->field('goods_id,goods_sn,goods_name,goods_name_style,cat_id,click_count,brand_id,goods_number,goods_weight,shop_price,market_price,promote_price,promote_start_date,promote_end_date,warn_number,goods_brief,goods_desc,goods_thumb,goods_img,original_img,is_real,extension_code,is_on_sale,is_alone_sale,integral,add_time,is_delete,is_new,is_hot,is_promote,bonus_type_id,last_update,goods_type,seller_note,give_integral')
                ->where($where)
                ->limit($pagearr['firstpage'] . ',' . C('page_size'))
                ->order('last_update desc,add_time desc,goods_id desc')
                ->select();
        }
        if ($res) {
            foreach ($res as $k => $v) {
                if ($v['goods_img']) {
                    $res[$k]['goods_thumb'] = img_init($v['goods_img']);
                }
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                // $val['is_presell']=D('Goodsstorage')->check_whether_presell($val['goods_id'],$wid);
            }


            $data = array('goodssaleslist' => $res, 'is_bottom' => $is_last, 'page' => $pagearr);
            return $data;
        } else {
            return false;
        }
    }

    /*
     * 收藏商品
     * */
    public function get_collect_goods($uid, $goods_id, $wid = 0)
    {
        $this->tableName = 'collect_goods';//收藏表
        $where = array('goods_id' => $goods_id, 'user_id' => $uid, 'wid' => $wid);
        $rec_id = M('collect_goods')->field('rec_id')->where($where)->find();
        if ($rec_id) {
            $data = array('is_attention' => 1);
            $id = $this->where($where)->save($data);
            if ($id !== false) {
                return $id;
            } else {
                return false;
            }
        } else {
            $data = array(
                'user_id' => $uid,
                'goods_id' => $goods_id,
                'add_time' => gmtime(),
                'is_attention' => 1,
                'wid' => $wid
            );
            $id = M('collect_goods')->add($data);
            if ($id) {
                return $id;
            } else {
                return false;
            }
        }
    }

    /*
     * 取消收藏
     * */

    public function cancel_collect_goods($uid, $goods_id, $wid = 0)
    {
        $this->tableName = 'collect_goods';//收藏表
        $where = array('goods_id' => $goods_id, 'user_id' => $uid, 'wid' => $wid);
        $rec_id = $this->fields('rec_id')->where($where)->find();
        if ($rec_id) {
            $data = array('is_attention' => 0);
            $id = $this->where($where)->save($data);
            if ($id !== false) {
                return $id;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    /* 搜索商品. */
    public function get_searchgoods($keyword, $page, $wid = 0, $uid)
    {
        $Model = new Model();

        if($wid == 0){
            $wid = 1;
        }

//        $where ['goods_name'] = array(
//            'like',
//            '%' . $keyword . '%'
//        );
//        $where ['is_on_sale'] = 1;
//        $where ['is_alone_sale'] = 1;
//        $where ['is_delete'] = 0;
//        $where ['goods_thumb'] = array("neq","");
//        $where['sources'] = array('neq', 891);
////            获取总数
//        $count = M("goods_wid_".$wid)->field('goods_id,goods_sn,goods_name,goods_name_style,cat_id,click_count,brand_id,goods_number,goods_weight,shop_price,market_price,promote_price,promote_start_date,promote_end_date,warn_number,goods_brief,goods_desc,goods_thumb,goods_img,original_img,is_real,extension_code,is_on_sale,is_alone_sale,integral,add_time,is_delete,is_new,is_hot,is_promote,bonus_type_id,last_update,goods_type,seller_note,give_integral,is_presell')
//            ->where($where)
//            ->count();

            $where = "is_supply = 1 "; //浏览商家供应商品
            $where2 = "g.is_supply = 1 "; //浏览商家供应商品


        $countsql = "
SELECT
	count(distinct(goods_id)) as goodssum
FROM
	sdx_goods_wid_".$wid."
WHERE
    ".$where." AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0  AND goods_thumb != '' AND goods_name like '%".$keyword."%'";

        //dump($countsql);
        $rescount = $Model->query($countsql);

        $count = $rescount[0]['goodssum'];


        $pagearr = show_page($count, $page);
        if ($page >= $pagearr ['pagecount']) {
            $is_last = 1;
        } else {
            $is_last = 0;
        }
////        获取搜索结果数据
//        $goodsData = M("goods_wid_".$wid)->field('real_num,fic_numgoods_id,sort_order,goods_sn,goods_name,goods_name_style,cat_id,click_count,brand_id,goods_number,goods_weight,shop_price,market_price,promote_price,promote_start_date,promote_end_date,warn_number,goods_brief,goods_desc,goods_thumb,goods_img,original_img,is_real,extension_code,is_on_sale,is_alone_sale,integral,add_time,is_delete,is_new,is_hot,is_promote,bonus_type_id,last_update,goods_type,seller_note,give_integral,goods_weight,spec_value,spec_unit,is_presell,delivery_type,delivery_cycle,virtual_sales,min_buy_num')
//            ->where($where)
//            ->limit($pagearr ['firstpage'] . ',' . C('page_size'))
//            ->order('real_num DESC,fic_num DESC,sort_order DESC,goods_id DESC')
//            ->select();

        $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num,
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and is_send_m ='0' and booking_time > ".strtotime("-3 days").") as b  on g.goods_id=b.goods_id
WHERE
    ".$where2." AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0  AND g.goods_thumb != '' AND g.goods_name like '%".$keyword."%'
     ORDER BY real_num DESC,fic_num DESC,sort_order DESC,goods_id DESC 
     LIMIT ".$pagearr ['firstpage'].",".C('page_size');




        $goodsData = $Model->query($sql);

        //dump(M("goods_wid_".$wid)->getlastsql());

        if ($goodsData) {
            $goods_list = $this->get_goods_price($goodsData, $wid, $uid,$user_platform);
            $data = array(
                'goodssaleslist' => $goods_list,
                'is_bottom' => $is_last,
                'total' => $count,
                'page' => $pagearr
            );
            return $data;
        } else {
            return false;
        }
    }

    /*
     *
     * 获取商品总数
     * */
    public function get_goodscount($where, $wid = 0)
    {
        if ($wid) {
            return $this->alias('g')
                ->where($where)
                ->join(C('DB_PREFIX') . 'goods_storage as gs on gs.goods_id=g.goods_id')
                ->count();
        } else {
            return $this->where($where)->count();
        }
    }

    /**
     *
     * 是否存在规格
     *
     * @access      public
     * @param       array $goods_attr_id_array 一维数组
     *
     * @return      string
     */
    public function is_spec($goods_attr_id_array, $sort = 'asc')
    {
        if (empty($goods_attr_id_array)) {
            return $goods_attr_id_array;
        }
        $Model = new Model();
        //重新排序
        $sql = "SELECT a.attr_type, v.attr_value, v.goods_attr_id
            FROM " . C('DB_PREFIX') . "attribute AS a
            LEFT JOIN " . C('DB_PREFIX') . "goods_attr AS v
                ON v.attr_id = a.attr_id
                AND a.attr_type = 1
            WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . "
                ORDER BY a.attr_id $sort";
        $row = $Model->query($sql);
        $return_arr = array();
        foreach ($row as $value) {
            $return_arr['sort'][] = $value['goods_attr_id'];
            $return_arr['row'][$value['goods_attr_id']] = $value;
        }
        if (!empty($return_arr)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取指定规格的货品信息
     *
     * @access      public
     * @param       string $goods_id
     * @param       array $spec_goods_attr_id
     * @return      array
     */
    public function get_products_info($goods_id, $spec_goods_attr_id)
    {
        $return_array = array();
        $Model = new Model();
        if (empty($spec_goods_attr_id) || !is_array($spec_goods_attr_id) || empty($goods_id)) {
            return $return_array;
        }

        $goods_attr_array = $this->sort_goods_attr_id_array($spec_goods_attr_id);

        if (isset($goods_attr_array['sort'])) {
            $goods_attr = implode('|', $goods_attr_array['sort']);

            $sql = "SELECT * FROM " . C('DB_PREFIX') . "products WHERE goods_id = '$goods_id' AND goods_attr = '$goods_attr' LIMIT 0, 1";
            $return_array = $Model->query($sql);
        }
        return $return_array[0];
    }

    /**
     * 将 goods_attr_id 的序列按照 attr_id 重新排序
     *
     * 注意：非规格属性的id会被排除
     *
     * @access      public
     * @param       array $goods_attr_id_array 一维数组
     * @param       string $sort 序号：asc|desc，默认为：asc
     *
     * @return      string
     */
    public function sort_goods_attr_id_array($goods_attr_id_array, $sort = 'asc')
    {
        $Model = new Model();
        if (empty($goods_attr_id_array)) {
            return $goods_attr_id_array;
        }

        //重新排序
        $sql = "SELECT a.attr_type, v.attr_value, v.goods_attr_id
            FROM " . C('DB_PREFIX') . "attribute AS a
            LEFT JOIN " . C('DB_PREFIX') . "goods_attr AS v
                ON v.attr_id = a.attr_id
                AND a.attr_type = 1
            WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . "
                ORDER BY a.attr_id $sort";
        $row = $Model->query($sql);

        $return_arr = array();
        foreach ($row as $key => $value) {
            $return_arr['sort'][] = $value['goods_attr_id'];

            $return_arr['row'][$value['goods_attr_id']] = $value;
        }

        return $return_arr;
    }


    /**
     * 返回商品原价
     * Created by Jerry
     * @param $goods_id
     * @return mixed
     */
    public function get_goods_price_for_discount_by_id($goods_id)
    {
        $where = array(
            'goods_id'  =>  $goods_id,
        );

        $data = $this->field('shop_price')->where($where)->find();
        return $data['shop_price'];
    }

    /**
     * 取得商品最终使用价格
     *
     * @param   string $goods_id 商品编号
     * @param   string $goods_num 购买数量
     * @param   boolean $is_spec_price 是否加入规格价格
     * @param   mix $spec 规格ID的数组或者逗号分隔的字符串
     *
     * @return  商品最终购买价格
     */
    public function get_final_price($goods_id, $goods_num = '1', $is_spec_price = false, $spec = array(), $uid)
    {
        $final_price = '0'; //商品最终购买价格
        $volume_price = '0'; //商品优惠价格
        $promote_price = '0'; //商品促销价格
        $user_price = '0'; //商品会员价格

        //取得商品优惠价格列表
        //$price_list = $this->get_volume_price_list($goods_id, '1');
        $price_list = array();  //目前不读取优惠
        $Model = new Model();
        if (!empty($price_list)) {
            foreach ($price_list as $value) {
                if ($goods_num >= $value['number']) {
                    $volume_price = $value['price'];
                }
            }
        }

        $user_rank = D('Users')->get_user_rank($uid);

        if(empty($user_rank['user_rank'])){
            $user_rank['user_rank'] = 1;
        }

        //取得商品促销价格列表
        /* 取得商品信息 */ /* 全场会员价 mp.user_rank = '" . $_SESSION['user_rank'] . "' */
        $sql = "SELECT g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.promote_goods_number, g.promote_today_number, g.promote_number, " .
            "IFNULL(mp.user_price, g.shop_price * '" . $user_rank['discount'] . "') AS shop_price " .
            " FROM " . C('DB_PREFIX') . "goods AS g " .
            " LEFT JOIN " . C('DB_PREFIX') . "supply_price AS mp " .
            "ON mp.goods_id = g.goods_id AND mp.user_rank= ".$user_rank['user_rank'] .
            " WHERE g.goods_id = '" . $goods_id . "'" .
            " AND g.is_delete = 0";
        $goods = $Model->query($sql);
        $goods = $goods[0];

        /* 计算商品的促销价格 */
        //目前不促销
//        if ($goods['promote_price'] > 0) {
//            $promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
//        } else {
//            $promote_price = 0;
//        }

        //取得商品会员价格列表
        $user_price = $goods['shop_price'];

//        if (floatval($user_price) <= 0) {
//			if (floatval($goods['market_price']) > 0) {
//				$user_price = $goods['market_price'];
//			}
//		}

        //比较商品的促销价格，会员价格，优惠价格
        if (empty($volume_price) && empty($promote_price)) {
            //如果优惠价格，促销价格都为空则取会员价格
            $final_price = $user_price;
        } elseif (!empty($volume_price) && empty($promote_price)) {
            //如果优惠价格为空时不参加这个比较。
            $final_price = min($volume_price, $user_price);
        } elseif (empty($volume_price) && !empty($promote_price)) {
            //如果促销价格为空时不参加这个比较。
            $final_price = min($promote_price, $user_price);
        } elseif (!empty($volume_price) && !empty($promote_price)) {
            //取促销价格，会员价格，优惠价格最小值
            $final_price = min($volume_price, $promote_price, $user_price);
        } else {
            $final_price = $user_price;
        }

        /**
         * 如果是第二件半价商品则统一使用原价计算
         */
//        $favourableModel = D('FavourableActivity');
//        if($favourableModel->get_is_discount($uid, $goods_id)){
//            $final_price = $this->get_goods_price_for_discount_by_id($goods_id);
//        }

        //如果需要加入规格价格
        if ($is_spec_price) {
            if (!empty($spec)) {
                $spec_price = $this->spec_price($spec);
                $final_price += $spec_price;
            }
        }


        $supply_discount = M("goods")->where(array("goods_id"=>$goods_id))->getField("supply_discount");
        $now_discount = 1;//默认无折扣
        if(!empty($supply_discount)){
            $supply_discount_list = array();
            $supply_discount = unserialize($supply_discount);
            foreach ($supply_discount as $supply_key=>$supply_vaule){
                if($supply_vaule["base"]<=$goods_num){
                    $supply_discount_list[$supply_vaule["base"]]=$supply_vaule["discount"];
                }
            }
            if(count($supply_discount_list)>0){
                $now_discount = end($supply_discount_list)/100;
            }
        }

        //返回商品最终购买价格
        return $final_price*$now_discount;
    }

    /**
     * 取得商品优惠价格列表
     *
     * @param   string $goods_id 商品编号
     * @param   string $price_type 价格类别(0为全店优惠比率，1为商品优惠价格，2为分类优惠比率)
     *
     * @return  优惠价格列表
     */
    public function get_volume_price_list($goods_id, $price_type = '1')
    {
        $volume_price = array();
        $temp_index = '0';
        $Model = new Model();
        $sql = "SELECT `volume_number` , `volume_price`" .
            " FROM " . C('DB_PREFIX') . "" .
            "volume_price WHERE `goods_id` = '" . $goods_id . "' AND `price_type` = '" . $price_type . "'" .
            " ORDER BY `volume_number`";

        $res = $Model->query($sql);
        foreach ($res as $k => $v) {
            $volume_price[$temp_index] = array();
            $volume_price[$temp_index]['number'] = $v['volume_number'];
            $volume_price[$temp_index]['price'] = $v['volume_price'];
            $volume_price[$temp_index]['format_price'] = price_format($v['volume_price']);
            $temp_index++;
        }
        return $volume_price;
    }

    /**
     * 获得指定的规格的价格
     *
     * @access  public
     * @param   mix $spec 规格ID的数组或者逗号分隔的字符串
     * @return  void
     */
    public function spec_price($spec)
    {
        if (!empty($spec)) {
            $Model = new Model();
            if (is_array($spec)) {
                foreach ($spec as $key => $val) {
                    $spec[$key] = addslashes($val);
                }
            } else {
                $spec = addslashes($spec);
            }

            $where = db_create_in($spec, 'goods_attr_id');

            $sql = 'SELECT SUM(attr_price) AS attr_price FROM ' . C('DB_PREFIX') . "goods_attr WHERE $where";
            $res = $Model->query($sql);
            $price = floatval($res[0]['attr_price']);
        } else {
            $price = 0;
        }
        return $price;
    }

    /**
     * 获得指定的商品属性
     *
     * @access      public
     * @param       array $arr 规格、属性ID数组
     * @param       type $type 设置返回结果类型：pice，显示价格，默认；no，不显示价格
     *
     * @return      string
     */
    public function get_goods_attr_info($arr, $type = 'pice')
    {
        $attr = '';

        if (!empty($arr)) {
            $fmt = "%s:%s[%s] \n";
            $Model = new Model();
            $sql = "SELECT a.attr_name, ga.attr_value, ga.attr_price " .
                "FROM " . C('DB_PREFIX') . "goods_attr AS ga, " .
                C('DB_PREFIX') . "attribute AS a " .
                "WHERE " . db_create_in($arr, 'ga.goods_attr_id') . " AND a.attr_id = ga.attr_id";
            $res = $Model->query($sql);
            foreach ($res as $key => $row) {
                $attr_price = round(floatval($row['attr_price']), 2);
                $attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
            }
            $attr = str_replace('[0]', '', $attr);
        }

        return $attr;
    }

    /**
     * 获得指定礼包的商品
     *
     * @access  public
     * @param   integer $package_id
     * @return  array
     */
    function get_package_goods($package_id)
    {
        $sql = "SELECT pg.goods_id, g.goods_name, pg.goods_number, p.goods_attr, p.product_number, p.product_id
            FROM " . C('DB_PREFIX') . 'package_goods ' . " AS pg
                LEFT JOIN " . C('DB_PREFIX') . 'goods ' . " AS g ON pg.goods_id = g.goods_id
                LEFT JOIN " . C('DB_PREFIX') . 'products ' . " AS p ON pg.product_id = p.product_id
                    WHERE pg.package_id = '$package_id'";
        if ($package_id == 0) {
            $sql .= " AND pg.admin_id = '$_SESSION[admin_id]'";
        }
        $Model = new Model();
        $resource = $Model->query($sql);
        if (!$resource) {
            return array();
        }

        $row = array();

        /* 生成结果数组 取存在货品的商品id 组合商品id与货品id */
        $good_product_str = '';
        foreach ($resource as $key => $_row) {
            if ($_row['product_id'] > 0) {
                /* 取存商品id */
                $good_product_str .= ',' . $_row['goods_id'];

                /* 组合商品id与货品id */
                $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id'];
            } else {
                /* 组合商品id与货品id */
                $_row['g_p'] = $_row['goods_id'];
            }

            //生成结果数组
            $row[] = $_row;
        }
        $good_product_str = trim($good_product_str, ',');

        /* 释放空间 */
        unset($resource, $_row, $sql);

        /* 取商品属性 */
        if ($good_product_str != '') {
            $sql = "SELECT goods_attr_id, attr_value FROM " . C('DB_PREFIX') . 'goods_attr' . " WHERE goods_id IN ($good_product_str)";
            $result_goods_attr = $Model->query($sql);

            $_goods_attr = array();
            foreach ($result_goods_attr as $key => $value) {
                $_goods_attr[$value['goods_attr_id']] = $value['attr_value'];
            }
        }

        /* 过滤货品 */
        $format[0] = '%s[%s]--[%d]';
        $format[1] = '%s--[%d]';
        foreach ($row as $key => $value) {
            if ($value['goods_attr'] != '') {
                $goods_attr_array = explode('|', $value['goods_attr']);

                $goods_attr = array();
                foreach ($goods_attr_array as $_attr) {
                    $goods_attr[] = $_goods_attr[$_attr];
                }

                $row[$key]['goods_name'] = sprintf($format[0], $value['goods_name'], implode('，', $goods_attr), $value['goods_number']);
            } else {
                $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['goods_number']);
            }
        }

        return $row;
    }

    /**
     * 获取商品销量总数
     *
     * @access public
     * @param integer $goods_id
     * @return integer
     */
    public function get_goods_sales_count($goods_id)
    {
        /* 查询该商品销量 */
        $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) as count ' .
            'FROM ' . C('DB_PREFIX') . 'order_info AS o, ' . C('DB_PREFIX') . 'order_goods AS g ' .
            "WHERE o . order_id = g . order_id " .
            " AND o . order_status in(1,5) AND o . shipping_status in(1,2) AND o . pay_status in(2,1)AND g . goods_id = '$goods_id'";
        $result = $this->query($sql);
        return $result[0]['count'];
    }

    /**
     * 获得指定商品的关联商品
     *
     * @access  public
     * @param   integer $goods_id
     * @return  array
     */
    public function get_linked_goods($goods_id)
    {
        foreach ($goods_id as $gid) {
            $goodsId[] = $gid['goods_id'];
        }
        $related_goods_number = C('related_goods_number') ? C('related_goods_number') : 0;
        $related_goods_number = $related_goods_number * 3;
        $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
            "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, " .
            'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . C('DB_PREFIX') . 'link_goods lg ' .
            'LEFT JOIN ' . C('DB_PREFIX') . 'goods AS g ON g.goods_id = lg.link_goods_id ' .
            "LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
            "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " .
            "WHERE lg.goods_id  " . db_create_in($goodsId) . " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " .
            "LIMIT " . $related_goods_number;
        $Model = new Model();
        $res = $Model->query($sql);

        $arr = array();
        foreach ($res as $key => $row) {
            if (!in_array($row['goods_id'], $goodsId)) {
                $arr[$row['goods_id']]['goods_id'] = $row['goods_id'];
                $arr[$row['goods_id']]['goods_name'] = $row['goods_name'];
                $arr[$row['goods_id']]['short_name'] = C('goods_name_length') > 0 ?
                    sub_str($row['goods_name'], C('goods_name_length')) : $row['goods_name'];
                $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], img_init($row['goods_thumb']), true);
                $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']);
                $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']);
                $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']);
                //$arr[$row['goods_id']]['url'] = url('goods/index', array('id' => $row['goods_id']));

                if ($row['promote_price'] > 0) {
                    $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
                    $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
                } else {
                    $arr[$row['goods_id']]['promote_price'] = 0;
                }
            }
        }
        //返回数组
        $related_goods_number = C('related_goods_number');
        if (count($arr) > $related_goods_number) {
            $linked_goods = array_rand($arr, $related_goods_number);
            foreach ($linked_goods as $key) {
                $array[] = $arr[$key];
            }
        } else {
            $array = $arr;
        }
        return $array;
    }


    /**
     * 获得购物车中商品的配件
     *
     * @access  public
     * @param   array $goods_list
     * @return  array
     */
    public function get_goods_fittings($goods_list = array())
    {
        $temp_index = 0;
        $arr = array();

        $sql = 'SELECT gg.parent_id, ggg.goods_name AS parent_name, gg.goods_id, gg.goods_price, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
            "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price " .
            'FROM ' . C('DB_PREFIX') . 'group_goods AS gg ' .
            'LEFT JOIN ' . C('DB_PREFIX') . 'goods AS g ON g.goods_id = gg.goods_id ' .
            "LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " .
            "ON mp.goods_id = gg.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " .
            "LEFT JOIN " . C('DB_PREFIX') . "goods AS ggg ON ggg.goods_id = gg.parent_id " .
            "WHERE gg.parent_id " . db_create_in($goods_list) . " AND g.is_delete = 0 AND g.is_on_sale = 1 " .
            "ORDER BY gg.parent_id, gg.goods_id";
        $Model = new Model();
        $res = $Model->query($sql);
        foreach ($res as $key => $value) {
            $arr[$temp_index]['parent_id'] = $value['parent_id'];
            $arr[$temp_index]['parent_name'] = $value['parent_name']; //配件的基本件的名称
            $arr[$temp_index]['parent_short_name'] = C('goods_name_length') > 0 ?
                sub_str($value['parent_name'], C('goods_name_length')) : $value['parent_name']; //配件的基本件显示的名称
            $arr[$temp_index]['goods_id'] = $value['goods_id']; //配件的商品ID
            $arr[$temp_index]['goods_name'] = $value['goods_name']; //配件的名称
            $arr[$temp_index]['short_name'] = C('goods_name_length') > 0 ?
                sub_str($value['goods_name'], C('goods_name_length')) : $value['goods_name']; //配件显示的名称
            $arr[$temp_index]['fittings_price'] = price_format($value['goods_price']); //配件价格
            $arr[$temp_index]['shop_price'] = price_format($value['shop_price']); //配件原价格
            $arr[$temp_index]['goods_thumb'] = get_image_path($value['goods_id'], img_init($value['goods_thumb']), true);
            $arr[$temp_index]['goods_img'] = get_image_path($value['goods_id'], img_init($value['goods_img']));
            // $arr[$temp_index]['url'] = url('goods/index', array('id' => $value['goods_id']));
            $temp_index++;
        }
        return $arr;
    }

    /**
     * 取得团购活动信息
     * @param   int $group_buy_id 团购活动id
     * @param   int $current_num 本次购买数量（计算当前价时要加上的数量）
     * @return  array
     *                  status          状态：
     */
    public function group_buy_info($group_buy_id, $current_num = 0)
    {
        /* 取得团购活动信息 */
        $group_buy_id = intval($group_buy_id);
        $sql = "SELECT *, a.act_id AS group_buy_id, a.act_desc AS group_buy_desc, a.start_time AS start_date, a.end_time AS end_date ,
        ta.sales_count ,ta.act_banner , ta.click_num " .
            "FROM " . C('DB_PREFIX') .
            "goods_activity as a LEFT JOIN " . C('DB_PREFIX') . 'touch_goods_activity as ta ON a.act_id = ta.act_id ' .
            "WHERE a.act_id = '$group_buy_id' " .
            "AND a.act_type = '" . GAT_GROUP_BUY . "' limit 1";
        $Model = new Model();
        $group_buy = $Model->query($sql);
        $group_buy = $group_buy[0];
        /* 如果为空，返回空数组 */
        if (empty($group_buy)) {
            return array();
        }

        $ext_info = unserialize($group_buy['ext_info']);
        $group_buy = array_merge($group_buy, $ext_info);

        /* 格式化时间 */
        $group_buy['formated_start_date'] = local_date('Y-m-d H:i', $group_buy['start_time']);
        $group_buy['formated_end_date'] = local_date('Y-m-d H:i', $group_buy['end_time']);

        /* 格式化保证金 */
        $group_buy['formated_deposit'] = price_format($group_buy['deposit'], false);

        /* 处理价格阶梯 */
        $price_ladder = $group_buy['price_ladder'];
        if (!is_array($price_ladder) || empty($price_ladder)) {
            $price_ladder = array(array('amount' => 0, 'price' => 0));
        } else {
            foreach ($price_ladder as $key => $amount_price) {
                $price_ladder[$key]['formated_price'] = price_format($amount_price['price'], false);
            }
        }
        $group_buy['price_ladder'] = $price_ladder;

        /* 统计信息 */
        $stat = $this->group_buy_stat($group_buy_id, $group_buy['deposit']);
        $group_buy = array_merge($group_buy, $stat);

        /* 计算当前价 */
        $cur_price = $price_ladder[0]['price']; // 初始化
        $cur_amount = $stat['valid_goods'] + $current_num; // 当前数量
        foreach ($price_ladder as $amount_price) {
            if ($cur_amount >= $amount_price['amount']) {
                $cur_price = $amount_price['price'];
            } else {
                break;
            }
        }
        $group_buy['cur_price'] = $cur_price;
        $group_buy['formated_cur_price'] = price_format($cur_price, false);

        /* 最终价 */
        $group_buy['trans_price'] = $group_buy['cur_price'];
        $group_buy['formated_trans_price'] = $group_buy['formated_cur_price'];
        $group_buy['trans_amount'] = $group_buy['valid_goods'];

        /* 状态 */
        $group_buy['status'] = $this->group_buy_status($group_buy);
        if (L('gbs.' . $group_buy['status']) != '') {
            $group_buy['status_desc'] = L('gbs.' . $group_buy['status']);
        }

        $group_buy['start_time'] = $group_buy['formated_start_date'];
        $group_buy['end_time'] = $group_buy['formated_end_date'];
        $group_buy['act_banner'] = $group_buy['act_banner'];
        $group_buy['click_num'] = $group_buy['click_num'];
        //$group_buy['sales_count'] = $group_buy['sales_count'] ? $group_buy['sales_count'] : 0;


        return $group_buy;
    }

    /*
     * 取得某团购活动统计信息
     * @param   int     $group_buy_id   团购活动id
     * @param   float   $deposit        保证金
     * @return  array   统计信息
     *                  total_order     总订单数
     *                  total_goods     总商品数
     *                  valid_order     有效订单数
     *                  valid_goods     有效商品数
     */

    public function group_buy_stat($group_buy_id, $deposit)
    {
        $group_buy_id = intval($group_buy_id);

        /* 取得团购活动商品ID */
        $sql = "SELECT goods_id " .
            "FROM " . C('DB_PREFIX') .
            "goods_activity WHERE act_id = '$group_buy_id' " .
            "AND act_type = '" . GAT_GROUP_BUY . "'";
        $Model = new Model();
        $result = $Model->query($sql);
        $group_buy_goods_id = $result[0]['goods_id'];

        /* 取得总订单数和总商品数 */
        $sql = "SELECT COUNT(*) AS total_order, SUM(g.goods_number) AS total_goods " .
            "FROM " . C('DB_PREFIX') . "order_info AS o, " .
            C('DB_PREFIX') . "order_goods AS g " .
            " WHERE o.order_id = g.order_id " .
            "AND o.extension_code = 'group_buy' " .
            "AND o.extension_id = '$group_buy_id' " .
            "AND g.goods_id = '$group_buy_goods_id' " .
            "AND (order_status = '" . OS_CONFIRMED . "' OR order_status = '" . OS_UNCONFIRMED . "')";
        $stat = $Model->query($sql);
        $stat = $stat[0];
        if ($stat['total_order'] == 0) {
            $stat['total_goods'] = 0;
        }

        /* 取得有效订单数和有效商品数 */
        $deposit = floatval($deposit);
        if ($deposit > 0 && $stat['total_order'] > 0) {
            $sql .= " AND (o.money_paid + o.surplus) >= '$deposit'";
            $row = $Model->query($sql);
            $row = $row[0];
            $stat['valid_order'] = $row['total_order'];
            if ($stat['valid_order'] == 0) {
                $stat['valid_goods'] = 0;
            } else {
                $stat['valid_goods'] = $row['total_goods'];
            }
        } else {
            $stat['valid_order'] = $stat['total_order'];
            $stat['valid_goods'] = $stat['total_goods'];
        }

        return $stat;
    }

    /**
     * 获得团购的状态
     *
     * @access  public
     * @param   array
     * @return  integer
     */
    function group_buy_status($group_buy)
    {
        $now = gmtime();
        if ($group_buy['is_finished'] == 0) {
            /* 未处理 */
            if ($now < $group_buy['start_time']) {
                $status = GBS_PRE_START;
            } elseif ($now > $group_buy['end_time']) {
                $status = GBS_FINISHED;
            } else {
                if ($group_buy['restrict_amount'] == 0 || $group_buy['valid_goods'] < $group_buy['restrict_amount']) {
                    $status = GBS_UNDER_WAY;
                } else {
                    $status = GBS_FINISHED;
                }
            }
        } elseif ($group_buy['is_finished'] == GBS_SUCCEED) {
            /* 已处理，团购成功 */
            $status = GBS_SUCCEED;
        } elseif ($group_buy['is_finished'] == GBS_FAIL) {
            /* 已处理，团购失败 */
            $status = GBS_FAIL;
        }
        

        return $status;
    }

    /**
     * 获取会员价格
     * Created by Jerry
     * @param $goods_id
     * @param $uid
     * @return mixed|null
     */
    public function get_vip_price($goods_id, $uid)
    {

        if(empty($uid)){
            $uid = I('post.uid');
        }

        if(empty($uid)){
            $price = M('goods')->where(array('goods_id'=>$goods_id))->getField('shop_price');
        }else{
            $user_rank = D('Users')->get_user_rank($uid);

            if(empty($user_rank)){
                $user_rank['user_rank'] = 1;
            }

            $price = D('supply_price')->where(array('goods_id' => $goods_id, 'user_rank' => $user_rank['user_rank']))->getField('user_price');

            if (!$price) {
                $price = $this->get_final_price($goods_id, 1, false, array(), $uid);
            }
        }

        /**
         * 如果是第二件半价商品则统一使用原价计算
         */
//        $favourableModel = D('FavourableActivity');
//        if($favourableModel->get_is_discount($uid, $goods_id)){
//            $price = $this->get_goods_price_for_discount_by_id($goods_id);
//        }


        $price = round($price,2);
        return number_format($price, 2, '.', '');
    }

    /**
     * 返回vip价格
     * Created by Jerry
     * @param $goods_id
     * @return mixed
     */
    public function get_vip_price_for_all($goods_id, $rank=2)
    {
        if(empty($user_rank)){
            $user_rank['user_rank'] = $rank;
        }

        $price = D('supply_price')->where(array('goods_id' => $goods_id, 'user_rank' => $user_rank['user_rank']))->getField('user_price');

        if (!$price) {
            $user_vip_rank = D('UserRank')->get_vip_rank();

            $where = array(
                'goods_id'  =>  $goods_id,
            );
            $field = "shop_price * ({$user_vip_rank['discount']} / 100) as price";
            $data = $this->field($field)->where($where)->find();
            $price = $data['price'];

        }

        $price = round($price,2);
        return number_format($price, 2, '.', '');
    }


    /**
     * 缺货登记
     * @param $goods_id
     * @param $uid
     * @param $user_phone
     * @return bool
     */
    public function book_goods($goods_id, $uid, $user_phone,$wid)
    {
        
        $booking_goods = M("booking_goods");
        $count = $booking_goods->where(array("user_id" => $uid,"is_send_m" =>'0',"goods_id" => $goods_id,"booking_time"=>array('gt',strtotime("-3 days"))))->count();
        
        
        if ($count > 0) {
            return false;
        } else {
           
            $data['user_id'] = $uid;
            $data['email'] = '0';
            $data['link_man'] = $user_phone;
            $data['tel'] = $user_phone;
            $data['goods_id'] = $goods_id;
            $data['goods_desc'] = M("goods")->where(array("goods_id" => $goods_id))->getField('goods_name');
            $data['goods_sn'] = M("goods")->where(array("goods_id" => $goods_id))->getField('goods_sn');
            $data['goods_number'] = 1;
            $data['wid'] = $wid;
            $data['booking_time'] = gmtime();
            
            $booking_goods->add($data);
            return true;
        }
    }
    
    /**
     * 判断缺货是否已登记
     * @param $goods_id
     * @param $uid
     * @param $user_phone
     * @return bool
     */
    public function is_book_goods($goods_id, $uid, $user_phone)
    {
        $booking_goods = M("booking_goods");
        $count = $booking_goods->where(array("user_id" => $uid,"is_send_m" => '0', "goods_id" => $goods_id,"booking_time"=>array('gt',strtotime("-3 days"))))->count();
        if ($count > 0) {
            return true;
        } else {
            return false;
        }
    }



    /**
     * 根据用户ID 获取手机绑定的手机号码
     * @param $uid
     * @return mixed
     */
    public function get_user_phone($uid)
    {
        return M("users")->where(array("user_id" => $uid))->getField('mobile_phone');
    }


    /**
     * 根据商品分类获取商品标签
     * @param $category_id
     * @return mixed
     */
    public function get_goods_tag_by_category($category_id,$wid=null,$internal_call=false)
    {
        $new_cat[] = $category_id;
        //查询此分类的子分类
        $category_array = M('category')->where(array("parent_id"=>$category_id,))->getField('cat_id',true);
        if(count($category_array)>0){
            array_push($category_array,$category_id);
            $new_cat = $category_array;
        }else{
            $new_cat = $category_id;
        }
        $where_category['relation_type'] = array("in",$new_cat);
        $new_tag = array();
        $goods_tag  = M("goods_tag")->where($where_category)->order('tag_sort ASC')->select();

        if(count($goods_tag)>0){
            foreach ($goods_tag as $key=>$value){
                $where['_string'] = "keywords LIKE '%".$value['tag_name']."%'";
                $where['is_on_sale'] = 1;
                $where['is_delete'] = 0;
                $where['goods_thumb'] = array("neq","");
                //取消限制本分类下的商品
                //$where['cat_id'] = array("in",$new_cat);

                $res_count = M('goods')->where($where)->count();
                if($res_count>0){
                    //unset($goods_tag[$key]);
                    $new_tag[] = array(
                        'id' => $value['id'],
                        'tag_name' => $value['tag_name'],
                        'relation_type' => $value['relation_type'],
                        'tag_sort' => $value['tag_sort']
                    );
                }
                //dump(M('goods')->getlastsql());
            }

        }
        if($internal_call){
            return $new_tag;
        }else{
            if(count($new_tag)>1){
                return $new_tag;
            }else{
                return array();
            }
        }


    }

    /**
     * 分类商品购买数量限制
     * @param int $goods_id
     */
    public function check_cat_max_buy_number($goods_data, $price, $uid, $num)
    {
        $cat_limit = C('CATE_BUY_LIMIT');
        $goods_info = $this->where(array('goods_id' => $goods_data['goods_id']))->find();
        $goods_limit = $cat_limit[$goods_info['cat_id']];
        if (!empty($goods_limit)) {
            $map['og.goods_id'] = $goods_info['goods_id'];
            $map['og.goods_price'] = $price;
            $map['og.goods_attr_id'] = $goods_data['goods_attr_id'] ? $goods_data['goods_attr_id'] : "";
            $map['og.parent_id'] = $goods_data['parent_id'] ? $goods_data['parent_id'] : 0;
            $map['og.is_quota'] = $goods_data['is_quota'] ? $goods_data['is_quota'] : 0;
            $map['og.is_gift'] = $goods_data['is_gift'] ? $goods_data['is_gift'] : 0;
            $map['og.extension_code'] = $goods_data['extension_code'] ? $goods_data['extension_code'] : "";
            $map['og.is_real'] = $goods_data['is_real'] ? $goods_data['is_real'] : 1;
            $map['oi.user_id'] = $uid;
            $map['oi.pay_status'] = array('eq', 2);
            if ($goods_limit['is_day'] == 1) {
                $begintime = strtotime(date("Y-m-d"));
                $endtime = strtotime(date("Y-m-d") . " 23:59:59");

                $map['oi.add_time'] = array(array('EGT', $begintime), array('ELT', $endtime));
            }
            $order_goods = M("order_goods");
            $count = $order_goods->alias('og')->join("left join " . C("DB_PREFIX") . "order_info oi on oi.order_id = og.order_id")->where($map)->count();
            $count += $num;
            if ($goods_limit['num'] > 0 && $count > $goods_limit['num']) {
            	if($goods_limit['is_day'] == 1){
            		returnApiError("活动商品" . $goods_info['goods_name'] . "每天只能购买" . $goods_limit['num'] . "份");
            	}else{
            		returnApiError("活动商品" . $goods_info['goods_name'] . "每人只能购买" . $goods_limit['num'] . "份");
            	}
                
            }
        }
    }


    /**
     * TODO 返回按分类搜索关键字结果
     * @param $keyword 关键字
     * @param $cid 分类id
     * @return array
     */
    public function get_search_goods_by_cat($keyword, $wid, $cid=0, $page = 1, $uid,$brand_id=0,$idstring,$is_cart_use=0,$act_id)
    {
        $Model = new Model();

        $where = "g.is_supply = 1  AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb !=''";
        if(!empty($keyword)){
            $where.=" AND g.goods_name LIKE '%".$keyword."%'";
        }
        if($cid){
            //获取当前分类的所有子分类
            $cid_array = S('ym_category_child_cat_id_by_parentid_'.$cid);
            if(empty($cat_list)){
                $cat_list = D('category')->cat_list($cid,0,false,0,false);
                $cid_array=array();
                foreach ($cat_list as $cate_val){
                    $cid_array[] = $cate_val['cat_id'];
                }
                array_push($cid_array,$cid);
                $cid_array = array_unique($cid_array);
                S('ym_category_child_cat_id_by_parentid_'.$cid,$cid_array,6*3600);
            }

//            $cid_array=array();
//            foreach(explode(',',$cid) as $item){
//                $category = M('category')->where(array("parent_id"=>$item))->getField('cat_id',true);
//                if(count($category)>0){
//                    array_push($category,$item);
//                }else{
//                    $category[] = $item;
//                }
//                $cid_array=array_merge($cid_array,$category);
//            }
            $cat_str = implode(",",$cid_array);
            $where .=" AND g.cat_id IN($cat_str)";
        }
        if($brand_id){
            $where .=" AND g.brand_id IN($brand_id)";
        }
        if($idstring){
            $where .=" AND g.goods_id IN($idstring)";
        }
        if($is_cart_use==1){
            $goods_id_list=M('cart')->where(array('user_id'=>$uid,'_string'=>"(act_id<>".$act_id." or is_check='0')"))->field('goods_id')->select();
            $goods_id_li=array();
            foreach($goods_id_list as $item){
                $goods_id_li[]=$item['goods_id'];
            }
            
            if(!empty($goods_id_li)){
            	$whereIn = implode(',',$goods_id_li);
            	$where .= " AND g.goods_id not IN({$whereIn})";
//                $where .=" AND g.goods_id not IN(".implode(',',$goods_id_li).")";
            }
        }
        

        $countsql = "
SELECT
	count(distinct(g.goods_id)) as goodssum
FROM
	sdx_goods_wid_".$wid." as g
WHERE
    ".$where;
        $rescount = $Model->query($countsql);
//        返回总条数
        $count = $rescount[0]['goodssum'];


//        返回分页数据
        $pageData = show_page($count, $page);
        $is_last = $this->is_last($page, $pageData['pagecount']);



        $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num,
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and is_send_m ='0' and booking_time > ".strtotime("-3 days").") as b on g.goods_id=b.goods_id
WHERE
    ".$where." ORDER BY real_num DESC,fic_num DESC,sort_order DESC,goods_id DESC 
     LIMIT ".$pageData ['firstpage'].",".C('page_size');

        $arr = $Model->query($sql);


//        返回格式化数据
        $data = $this->get_goods_price($arr, $wid, $uid);

        return array(
            'goodssaleslist' => $data,
            'is_bottom' => $is_last,
            'total' => $count,
            'page' => $pageData,

        );

    }

    /**
     * TODO 返回按商品id搜索结果
     * @param $id
     * @param $uid
     * @param $wid
     * @return array
     */
    public function get_search_goods_by_id($id, $uid, $wid)
    {

        $Model = new Model();
        $where = "g.goods_id in($id) AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb !=''";
        $sql = "
SELECT g.*,
IF (g.practical_num > 0, 1, 0) AS real_num,
IF (g.goods_number > 0, 1, 0) AS fic_num,
IF (b.goods_number > 0, 1, 0) AS is_booking
FROM
	sdx_goods_wid_".$wid." as g left join (select goods_number,goods_id from sdx_booking_goods where user_id='".$uid."' and is_send_m ='0' and booking_time > ".strtotime("-3 days").") as b on g.goods_id=b.goods_id
WHERE ".$where;

        $arr = $Model->query($sql);

//        返回格式化数据
        $data = $this->get_goods_price($arr, $wid, $uid);

        return $data;

    }

    /*
     * 返回推荐商品列表
     * @param $wid 仓库id
     * @param $uid 用户id
     * @param $map
     * @param $limit
     * return array
     */
    public function get_recomment_goods($wid, $uid, $map, $limit){
        $arr = M('goods_wid_'.$wid)->where($map)->limit($limit)->select();
        $data = $this->get_goods_price($arr, $wid, $uid);
        return $data;
    }

    /*
     * 返回热销商品（同类品牌推荐、同类热销商品）
     * Created by caicm
     * @param $wid 仓库id
     * @param $uid 用户id
     * @param $type 查询类型（brand:品牌 category：分类）
     * @param $limit
     * return array
     */
    public function get_hot_sell_goods($wid, $uid, $goods_id, $type, $val, $limit=6){
        if($type == 'brand'){
            $where = "g.brand_id=$val AND ";
        }elseif($type == 'category'){
            $where = "g.cat_id in ($val) AND ";
        }
        $Model = new Model();

        $where .= " g.goods_id !=$goods_id AND g.is_on_sale = 1 AND cat_id!=151 AND is_offline=0 AND g.practical_num!=0 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_thumb !=''";
        $sql = "
SELECT 
(SELECT sum(goods_number) FROM `sdx_order_goods` as o WHERE o.goods_id=g.goods_id) as sale_num,g.*
FROM sdx_goods_wid_$wid as g WHERE $where order by sale_num DESC limit $limit";

        $arr = $Model->query($sql);
        $data = $this->get_goods_price($arr, $wid, $uid);
        return $data;
    }
    
    /**
     * 返回按品牌搜索关键字结果
     * @param $keyword 关键字
     * @param $brand_id 品牌id
     * @return array
     */
    public function get_search_goods_by_brand($keyword, $wid, $page = 1, $uid,$brand_id=0)
    {
    
        $where = $this->get_search_goods_brand_where($keyword, $brand_id);
    
        //        返回总条数
        $count = $this->where($where)->count();
    
        //        返回分页数据
        $pageData = show_page($count, $page);
        $is_last = $this->is_last($page, $pageData['pagecount']);
    
    
        $arr = $this->where($where)
        ->limit($pageData ['firstpage'] . ',' . C('page_size'))
        ->order('last_update desc,add_time desc,goods_id desc')
        ->select();
    
        //        返回格式化数据
        $data = $this->get_goods_price($arr, $wid, $uid);
    
        return array(
            'goodssaleslist' => $data,
            'is_bottom' => $is_last,
            'total' => $count,
            'page' => $pageData,
    
        );
    
    }


    /**
     * 返回分类搜索条件
     * Created by Jerry
     * @param $keyword
     * @return array
     */
    protected function get_search_goods_where($keyword)
    {
        return array(
            'goods_name' => array('like', "%{$keyword}%"),
            'is_on_sale' => 1,
            'is_alone_sale' => 1,
            'is_delete' => 0,
            'goods_thumb' => array("neq",""),
            'sources'   =>  array('neq', 891),
        );
    }
    
    /**
     * 返回搜索条件
     * @param $keyword
     * @param $cid
     * @return array
     */
    protected function get_search_goods_brand_where($keyword, $brand_id)
    {
        return array(
            'goods_name' => array('like', "%{$keyword}%"),
            'brand_id' => $brand_id,
            'is_on_sale' => 1,
            'is_alone_sale' => 1,
            'is_delete' => 0,
            //            'sources'   =>  array('neq', 891),
        );
    }

    /**
     * 判断是否为最后一页
     * @param $page
     * @param $pagecount
     * @return int
     */
    protected function is_last($page, $pagecount)
    {
        if ($page >= $pagecount) {
            return 1;
        }

        return 0;
    }


    /**
     * 返回处理过后的商品数据
     * @param $data 商品数据
     * @param int $wid 仓库id
     * @return array
     */
    protected function get_goods_price($data, $wid = 0, $uid,$user_platform = 0)
    {
        if($wid == 0){
            $wid = 1;
        }

//        获取oss配置
//        $ossConfig = C('OSS');

        foreach ($data as $key => $val) {
             if(isset($val ['is_booking'])){
                 $goods ['is_booking'] = $val ['is_booking'];
             }
//            if ($val ['promote_price'] > 0) {
//                $promote_price = bargain_price($val ['promote_price'], $val ['promote_start_date'], $val ['promote_end_date']);
//                // $goods['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
//                $goods ['promote_price'] = $promote_price;
//            } else {
//                $goods ['promote_price'] = '';
//            }

//            if(localtotime($val['promote_end_date'] > gmtime())){
//                $goods['promote_price'] = $val['promote_price'];
//            }
			$goods['promote_price'] = bargain_price($val['promote_price'], $val ['promote_start_date'], $val ['promote_end_date']);
			if ($goods['promote_price'] > 0) {
				$goods['promote_start_date'] = date('Y-m-d', localtotime($val['promote_start_date']));
				$goods['promote_end_date'] = date('Y-m-d', localtotime($val['promote_end_date']));
				$promoteService = new PromoteService();
				$goods['promote_message'] = $promoteService->getPromoteGoodsNumber($val)->getNumberMessage();
			}else{
				unset($goods['promote_start_date'], $goods['promote_end_date'], $goods['promote_message']);
				$goods['promote_price'] = 0;
			}
            //促销价
            if ($val['is_buynow'] == 0 || $val['is_promote'] == 1) {
				$promoteService = new PromoteService();
				$goods = $promoteService->formatPromoteData($val);
            }
//            秒杀
            else if($val['is_buynow'] == 1){
				$buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
				$goods = $buyNowGoodsService->handleBuyNowGoodsData($val);
				unset($goods['promote_number']);
			}
//            else{
//            	unset($goods['promote_start_date'], $goods['promote_end_date'], $goods['promote_message']);
//				$goods['promote_price'] = 0;
//			}

            $goods ['goods_id'] = $val ['goods_id'];
            $goods ['market_price'] = trim($this->get_vip_price_for_all($val['goods_id'],1));    //市场价使用注册会员价
            $goods ['goods_number'] = $val ['goods_number'];
            $goods ['goods_brief'] = $val ['goods_brief'];
            $goods ['goods_desc'] = $val ['goods_desc'];
            $goods ['goods_name'] = $val ['goods_name'];
            if($user_platform==1){
                $goods ['shop_price'] = $val ['shop_price'];    //注册商家价
                $goods ['vip_price'] = $this->get_vip_price($val ['goods_id'], $uid);   //VIP商家价格
                $goods['true_vip_price'] = trim($this->get_vip_price_for_all($val['goods_id']));//vip商家对比价
            }else{
                $goods ['shop_price'] = $val ['shop_price'];    //注册会员价
                $goods ['vip_price'] = $this->get_vip_price($val ['goods_id'], $uid);   //VIP价格
                $goods['true_vip_price'] = trim($this->get_vip_price_for_all($val['goods_id']));//vip对比价
            }


            $goods['is_offline'] = $val['is_offline'];



            if ($wid) {
                $goods['wid'] = $val['wid'];
            } else {
                $goods['wid'] = 0;
            }

//            if ($val ['goods_thumb']) {
//                $goods ['goods_thumb'] = $val ['goods_thumb'];
//            } else {
//                $goods ['goods_thumb'] = $ossConfig['image_url'] . $val['goods_img'] . $ossConfig['thumb'];
//            }
//
//            $goods ['goods_img'] = $ossConfig['image_url'] . $val ['goods_img'];

            if ($val ['goods_img']) {
                $goods ['goods_thumb'] = img_init($val ['goods_img']);
            } else {
                $goods ['goods_thumb'] = img_init($val ['goods_thumb']);
            }

            $goods ['goods_img'] = img_init($val ['goods_img']);

            if ($val ['spec_value']) {
                $goods ['spec_value'] = $val ['spec_value'];
                $goods ['spec_unit'] = $val ['spec_unit'];
            } elseif ($val ['goods_weight']) {
                $goods ['spec_value'] = $val ['goods_weight'] * 1000;
                $goods ['spec_unit'] = "g";
            }

            $goods['min_buy_num'] = $val['min_buy_num'];
            $val['is_presell']=(int)$val['is_presell'];
            if($val['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $val['is_presell'] = D('Goodsstorage')->check_whether_presell($goods['goods_id'], $wid);
            }
            $goods['is_presell'] = $val['is_presell'];
            if ($val['is_presell']) {
                if ($val['delivery_type'] == 1) {
                    $Goodspreselltime = D('Goodspreselltime');
                    if ($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])) {//检查预售商品是否设置发货配送时间
                        $preselltimeres = $Goodspreselltime->check_shippingtime($goods['goods_id'], time());
                        if ($preselltimeres) {
                            $goods['preselltimeres'] = array('delivery_time' => $preselltimeres['delivery_time']);;
                        } else {
                            $goods['preselltimeres'] = array('delivery_time' => '');
                        }
                    } else {
                        $goods['preselltimeres'] = array('delivery_time' => '');
                    }
                } elseif ($val['delivery_type'] == 2) {
                    if ($val['delivery_cycle']) {
                        $gmd = local_date('Y-m-d', gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd . ' +' . $val['delivery_cycle'] . ' day ' . C('DEFAULT_PRESELL_TIME_H')));
                        $goods['preselltimeres'] = array('delivery_time' => $goods_presell_time);
                    } else {
                        $goods['preselltimeres'] = array('delivery_time' => '');
                    }
                } else {
                    $goods['preselltimeres'] = array('delivery_time' => '');
                }
            } else {
                $goodsstorage = D('Goodsstorage')->get_warehous_goods($wid, $val['goods_id']);
                if ($goodsstorage) {
                    $goods['goods_number'] = $goodsstorage['practical_num'];
                } else {
                    $goods['goods_number'] = 0;
                }
                $goods['preselltimeres'] = array('id' => '');
            }
            $goods_list[] = $goods;
        }

        return $goods_list;
    }

    /**
     * 返回指定来源的商品
     * Created by Jerry
     * @param array $where
     * @return mixed
     */
    public function get_goods_by_sources($where = array())
    {
        return $this->where($where)->select();
    }

	/**
	 * 返回所有促销价
	 * Created by Jerry
	 * @return mixed
	 */
	public function get_sales_goods_by_promote_price_for_list()
	{
		$where = array(
			'promote_price'		=>	array('GT', 0),	//促销价大于0
			'promote_start_date'=>	array('GT', 0),//促销时间大于0
			'promote_end_date'	=>	array('GT', 0),//促销时间大于0
			'is_delete'			=>	array('EQ', 0),//未删除
			'is_buynow'			=>	0,
		);

		$field = 'goods_sn, goods_id, goods_name, promote_start_date, promote_end_date';
		return $this->field($field)->where($where)->select();
	}

	/**
	 * 返回所有秒杀价
	 * Created by Jerry
	 * @return mixed
	 */
	public function get_sales_goods_by_is_buynow_for_list()
	{
		$where = array(
			'is_buynow'			=>	1,	//秒杀价
			'is_delete'			=>	array('EQ', 0),//未删除
			'is_on_sale'		=>	1,
		);

		$field = 'goods_sn, goods_id, goods_name, promote_start_date, promote_end_date';
		return $this->field($field)->where($where)->select();
	}


	/**
	 * 返回指定促销价商品
	 * Created by Jerry
	 * @param $goods_id
	 * @return mixed
	 */
	public function get_goods_info_by_promote($goods_id)
	{
		$where = array(
			'goods_id'	=>	$goods_id,
		);

		$field = 'goods_id, goods_sn, goods_name, shop_price, promote_price, promote_start_date, promote_end_date, promote_goods_number, promote_today_number, promote_number, is_buynow, is_offline';

		return $this->field($field)->where($where)->find(false);
	}

	/**
	 * 返回专题商品详情
	 * Created by Jerry
	 * @param $id
	 * @return mixed
	 */
	public function find_goods_for_seminar_by_id($id)
	{
		$where = array(
			'goods_id'	=>	$id,
		);
		$field = 'goods_name, goods_thumb, goods_img, goods_brief, is_presell, promote_price, promote_start_date, promote_end_date, goods_number, warn_number, original_img, is_on_sale';

		return $this->field($field)->where($where)->find();
	}


	/**
	 * 返回商品详细描述
	 * Created by Jerry
	 * @param $goods_id
	 * @return mixed
	 */
	public function find_goods_desc_by_goods_id($goods_id)
	{
		$where = array(
			'goods_id'	=>	$goods_id,
		);

		return $this->where($where)->getField('goods_desc');
	}


	/**
	 * 返回秒杀商品详情
	 * Created by Jerry
	 * @param $goods_id
	 * @return mixed
	 */
	public function findBuyNowGoodsInfoByGoodsId($goods_id)
	{
		$where = array(
			'goods_id'		=>	$goods_id,
			'is_buynow'		=>	1,
			'is_delete'		=>	0,
			'is_on_sale'	=>	array('NEQ', 0),
			'original_img'	=>	array('NEQ', ''),
		);

		$field = 'goods_name, goods_thumb, goods_img, goods_brief, is_presell, promote_price, promote_start_date, promote_end_date, goods_number, warn_number, original_img, is_on_sale, promote_goods_number, promote_today_number, is_buynow';

		return $this->field($field)->where($where)->find();
	}

	/**
	 * 返回891接口所有商品数据
	 * Created by Jerry
	 * @param $page
	 * @param $sku
	 * @param $barCode
	 * @return mixed
	 */
	public function findNoDeleteGoodsForAll($page, $sku, $barCode)
	{
		$where = array(
			'is_delete'	=>	0,
		);

		if (!empty($sku)) {
			$where['goods_id'] = $sku;
		}

		if (!empty($barCode)) {
			$where['goods_sn'] = $barCode;
		}

		$field = 'g.goods_name, g.goods_id, g.goods_sn, g.is_on_sale, g.goods_weight, g.seller_note, g.origin, g.sku, g.cat_id, g.brand_id, g.tax_rate, g.original_img, g.goods_desc, c.cat_name, b.brand_name, g.specs, ws.name as sup_name, ws.id as sup_id';

		return $this
				->alias('g')
				->field($field)
				->join('LEFT JOIN __CATEGORY__ AS c ON c.cat_id = g.cat_id')
				->join('LEFT JOIN __BRAND__ AS b ON b.brand_id = g.brand_id')
				->join('LEFT JOIN __WAREHOUSE_PROCUREMENT_DETAIL__ AS wpd ON wpd.goods_sn = g.goods_sn')
				->join('LEFT JOIN __WAREHOUSE_PROCUREMENT__ AS wp ON wp.id = wpd.procurement_id')
				->join('LEFT JOIN __WAREHOUSE_SUPPLIER__ AS ws ON ws.id = wp.supplier_id')
				->where($where)
				->limit($page['firstpage'], $page['pagesize'])
				->select();
	}

	/**
	 * Created by Jerry
	 * @param $category_id
	 * @param $goods_where
	 * @return bool|mixed
	 */
	public function findCategoryGoodsByCategoryId($category_id, $goods_where)
	{
		$categoryShowType = array(
			1	=>	20,
			2	=>	30,
			3	=>	50,
		);

		$categoryNewType = array(
			4	=>	20,
			5	=>	30,
			6	=>	50,
		);

		$where = false;

		if (array_key_exists($goods_where, $categoryShowType)) {
			$where = true;

			$sql = "SELECT
							g.goods_id
						FROM
							sdx_goods AS g
						LEFT JOIN (
							SELECT
								count(goods_id) AS num,
								goods_id
							FROM
								sdx_comment_goods
							GROUP BY
								goods_id
						) AS cg ON g.goods_id = cg.goods_id
						WHERE
							g.cat_id = '{$category_id}'
							AND g.is_delete = 0
							AND g.original_img != ''
						ORDER BY
							cg.num DESC
						LIMIT {$categoryShowType[$goods_where]}";

		}

		if (array_key_exists($goods_where, $categoryNewType)) {
			$where = true;
			$sql = "SELECT * FROM sdx_goods WHERE cat_id = '{$category_id}' AND is_delete = 0 AND original_img != '' ORDER BY add_time DESC LIMIT " . $categoryNewType[$goods_where];
		}

		if ($where == false){
			$sql = "SELECT * FROM sdx_goods WHERE cat_id = '{$category_id}' AND is_delete = 0 AND original_img != ''";
		}

		if (!isset($sql)) {
			return false;
		}

		$data = $this->query($sql);

		return $data;
	}

	/**
	 * 返回所有商品总条数
	 * Created by Jerry
	 * @param $sku
	 * @param $barCode
	 * @return mixed
	 */
	public function findNoDeleteGoodsForAllCount($sku, $barCode)
	{
		$where = array(
			'is_delete'	=>	0,
		);

		if (!empty($sku)) {
			$where['goods_id'] = $sku;
		}

		if (!empty($barCode)) {
			$where['goods_sn'] = $barCode;
		}



		$field = 'goods_id';

		return $this->field($field)->where($where)->count();
	}

	/**
	 * 返回指定修改时间商品总条数
	 * Created by Jerry
	 * @param $startTime
	 * @param $sku
	 * @param $barCode
	 * @return mixed
	 */
	public function findNoDeleteGoodsByLastUpdateCount($startTime, $sku, $barCode)
	{
		$where = array(
			'is_delete'		=>	0,
			'last_update'	=>	array('EGT', $startTime),	//大于等于修改时间
		);

		if (!empty($sku)) {
			$where['goods_id'] = $sku;
		}

		if (!empty($barCode)) {
			$where['goods_sn'] = $barCode;
		}

		$field = 'goods_id';

		return $this->field($field)->where($where)->count();
	}


	/**
	 * 返回所有指定修改时间后的商品
	 * Created by Jerry
	 * @param $startTime
	 * @param $page
	 * @param $sku
	 * @param $barCode
	 * @return mixed
	 */
	public function findNoDeleteGoodsByLastUpdate($startTime, $page, $sku, $barCode)
	{

		$where = array(
			'g.is_delete'		=>	0,
			'g.last_update'	=>	array('EGT', $startTime),	//大于等于修改时间
		);

		if (!empty($sku)) {
			$where['g.goods_id'] = $sku;
		}

		if (!empty($barCode)) {
			$where['g.goods_sn'] = $barCode;
		}

//		$field = 'g.goods_name, g.goods_id, g.goods_sn, g.is_on_sale, g.goods_weight, g.seller_note, g.origin, g.sku, g.cat_id, g.brand_id, g.tax_rate, g.original_img, g.goods_desc, c.cat_name, b.brand_name, g.last_update, g.specs';
		$field = 'g.goods_name, g.goods_id, g.goods_sn, g.is_on_sale, g.goods_weight, g.seller_note, g.origin, g.sku, g.cat_id, g.brand_id, g.tax_rate, g.original_img, g.goods_desc, c.cat_name, b.brand_name, g.specs, ws.name as sup_name, ws.id as sup_id';

		return $this
			->alias('g')
			->field($field)
			->join('LEFT JOIN __CATEGORY__ AS c ON c.cat_id = g.cat_id')
			->join('LEFT JOIN __BRAND__ AS b ON b.brand_id = g.brand_id')
			->join('LEFT JOIN __WAREHOUSE_PROCUREMENT_DETAIL__ AS wpd ON wpd.goods_sn = g.goods_sn')
			->join('LEFT JOIN __WAREHOUSE_PROCUREMENT__ AS wp ON wp.id = wpd.procurement_id')
			->join('LEFT JOIN __WAREHOUSE_SUPPLIER__ AS ws ON ws.id = wp.supplier_id')
			->where($where)
			->limit($page['firstpage'], $page['pagesize'])
			->order('g.last_update asc')
			->select();
	}

	/**
	 * 获取秒杀商品
	 * Created by Jerry
	 * @param $startTime
	 * @param $endTime
	 * @return mixed
	 */
	public function findGoodsBuyNowListByPromoteTime($startTime, $endTime)
	{
		$where = array(
			'is_delete'			=>	0,
			'is_on_sale'		=>	1,
			'is_buynow'			=>	1,
			'original_img'		=>	array('NEQ', ''),
			'promote_start_date'=>	array('EGT', $startTime),
			'promote_end_date'=>	array('LT', $endTime),
		);

		$field = 'goods_id, goods_sn, goods_name, promote_start_date, promote_end_date, promote_price, promote_goods_number, promote_today_number, is_buynow, goods_thumb, goods_img, original_img, is_presell, goods_brief, delivery_type, delivery_cycle, warn_number, spec_unit, spec_value, min_buy_num, goods_number';

		return $this
			->field($field)
			->where($where)
			->order('promote_start_date ASC,add_time DESC')
			->select();
	}
}